﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IESN.Common;
using System.Threading;
using IESN.DM;
using Microsoft.VisualBasic;
using IESN.Tools;
using System.Collections;
using Microsoft.VisualBasic.CompilerServices;
using System.Windows.Forms;
using IESN.BaseForms;

namespace IESN.BusinessCore
{
    public class Controller : IDisposable
    {
        private delegate void ReadDMDelegate(DmClass obj1);

        public TimerState _TimerState;
        private TimerCallback timerDelegate;
        private Worker mworker;

        #region 属性

        /// <summary>
        /// DM对象的数量
        /// </summary>
        public short DmObjectCollectCount
        {
            get
            {
                return (short)GlobalCache.GetInstance.DmMapping.Count;
            }
        }

        private bool _isRunning;  //原mRunning
        /// <summary>
        /// Background process already running
        /// 后台线程是否正在运行
        /// </summary>
        public bool IsRunning
        {
            get
            {
                return this._isRunning;
            }
            set
            {
                this._isRunning = value;
            }
        }

        private bool _isOnLine;
        /// <summary>
        /// PLC是否在线标志
        /// </summary>
        public bool IsOnLine
        {
            get
            {
                return this._isOnLine;
            }
            set
            {
                this._isOnLine = value;
            }
        }

        private bool _PauseWorkerThread;
        /// <summary>
        /// 停止worker线程
        /// </summary>
        public bool PauseWorkerThread
        {
            get
            {
                return this._PauseWorkerThread;
            }
            set
            {
                this._PauseWorkerThread = value;
            }
        }

        #endregion
        
        /// <summary>
        /// 天车当前的位置 待确认 XP current position ?
        /// </summary>
        public short[] XPCurLoc;
        public short intHaveRectStageS;
        public short intNumRect_ForPreset;

         /// <summary>
        /// 初始化所有基本参数
        /// </summary>
        /// <param name="dbPath"></param>
        public Controller()
        { 
            //以下计时器的作用不明
            this._TimerState = new TimerState();
            this.timerDelegate = new TimerCallback(this.CheckStatus);
            System.Threading.Timer timer = new System.Threading.Timer(this.timerDelegate, this._TimerState, -1, Initialization.timerPeriod); //Timer 事件  CheckStatus(object state)
            this._TimerState.tmr = timer;

            this.XPCurLoc = new short[Initialization.TryGetParameterIntValue("NumXP")];
            intHaveRectStageS = 0;
            //this.intNumRect_ForPreset = (short)this._Rect_PresetTable.Rows.Count; //需要预设的整流机数量
        }

        private void CheckStatus(object state)
        {

        }

        public void Start(Worker theWorker)
        {
            this.mworker = theWorker;
            this.mworker.Initialize(this);

            if (this._isRunning)
            {
                throw new Exception("Background process already running");
            }
            this._isRunning = true;
            this._PauseWorkerThread = false;
           
            //if (!this.checktime())  LGH注释
            //{
                ThreadPool.QueueUserWorkItem(new WaitCallback(this.mworker.Start));
                //this._Talker.start();
                //this.startTPP_PRC(); //PRC ????
            //}
        }

        /// <summary>
        /// 刷新天车当前位置
        /// </summary>
        /// <param name="obj1"></param>
        public void RefreshXPCurLoc(DmClass obj1)
        {
            short start = 1;
            try
            {
                short numXP = (short)Initialization.TryGetParameterIntValue("NumXP");
                for (short i = 1; i <= numXP; i = (short)(i + 1))
                {
                    short num;
                    short num3;
                    //Application.DoEvents();
                    //Application.DoEvents();
                    if (Initialization.TryGetParameterIntValue("StageNoMaxLength") == 2)
                    {
                        num3 = (short)Math.Round(Conversion.Val(Strings.Mid(obj1.DmContent, start + 2, 2)));
                        num = (short)Math.Round(Conversion.Val(Strings.Mid(obj1.DmContent, start, 2)));
                    }
                    else
                    {
                        num3 = (short)Math.Round(Conversion.Val(Strings.Mid(obj1.DmContent, start + 4, 4)));
                        num = (short)Math.Round(Conversion.Val(Strings.Mid(obj1.DmContent, start, 4)));
                    }

                    //Application.DoEvents();
                    //Application.DoEvents();
                    this.XPCurLoc[i - 1] = num3;
                    if (Initialization.TryGetParameterIntValue("StageNoMaxLength") == 2)
                    {
                        start = (short)(start + 12);
                    }
                    else
                    {
                        start = (short)(start + 0x10);
                    }
                }
                obj1.DmRunEventProcessThreadStatus = true;
            }
            catch (Exception exception1)
            {
                LogHelper.Instance.Error(exception1.Message, exception1);
            }
        }

        /// <summary>
        /// 各自界面读DM
        /// </summary>
        /// <param name="obj"></param>
        public void ReadDM(DmClass obj)
        {
            string frmName = "";
            DmClass[] args = new DmClass[] { obj };
            IEnumerator enumerator = obj.DmWhichFormUsed.GetEnumerator();
            try
            {
                while (enumerator.MoveNext())
                {
                    frmName = StringType.FromObject(enumerator.Current);
                    if (this.FrmExistInCollect(frmName))
                    {
                        //this._FormListLock.AcquireReaderLock(-1);
                        Form form = (Form)this._formListCollect[frmName];

                        //this._FormListLock.ReleaseReaderLock();
                        if (form != null)
                        {
                            try
                            {
                                IClient client1 = (IClient)form;
                                ReadDMDelegate method = new ReadDMDelegate(client1.ReadDM);
                                try
                                {
                                    form.BeginInvoke(method, args);
                                }
                                catch (Exception exception1)
                                {
                                    ProjectData.SetProjectError(exception1);
                                    Exception objException = exception1;
                                    //this.LogError(objException);
                                    ProjectData.ClearProjectError();
                                }
                                continue;
                            }
                            catch (Exception exception4)
                            {
                                ProjectData.SetProjectError(exception4);
                                Exception exception2 = exception4;
                                //this.LogError(exception2);
                                ProjectData.ClearProjectError();
                                continue;
                            }
                        }
                    }
                }
            }
            catch (Exception exception5)
            {
                ProjectData.SetProjectError(exception5);
                Exception exception3 = exception5;
                //this.LogError(exception3);
                ProjectData.ClearProjectError();
            }
        }


        #region DM 事件

        public void ProcessCondi(DmClass obj1)
        {
            //To do 
        }

        public void GenNewPcode(DmClass obj1)
        {
           //To do
        } 

        public void SaveUnloadTodb(DmClass obj1)
        {
            //To do
        }

        public void RefreshPcodeOnXPArry(DmClass obj1)
        {
            //To do
        }

        public void RefreshNew_CMM_F_Arry(DmClass obj1)
        {
            //To do 
        }

        public void RefreshPcodeArry(DmClass obj1)
        {
            //To do
        }

        public void RefreshFBArry(DmClass obj1)
        {
            //To do 
        }

        public void RefreshLoading(DmClass obj1)
        {
            //To do 
        }

        public void RefreshImmTimeArry(DmClass obj1)
        {
            //To do 
        }

        public void GenEloadActionFlag(DmClass obj1)
        {
            //To do 
        }

        public void GenEloadPcode(DmClass obj1)
        {
            //To do 
        }

        public void RefreshReadEloadStageNo(DmClass obj1)
        {
            //To do 
        }

        public void SaveEloadTodb(DmClass obj1)
        {
            //To do 
        }

        public void RefreshAMPArry(DmClass obj1)
        {
            //To do 
        }

        public void RefreshTemperatureArry(DmClass obj1)
        {
            //To do 
        }

        public void RefreshDosDahPumpStatusArry(DmClass obj1)
        {
            //To do 
        }

        public void RefreshCMDosingPumpArry(DmClass obj1)
        {
            //To do 
        }

        public void RefreshActCMArry(DmClass obj1)
        {
            //To do 
        }

        public void RefreshACTDAHArry(DmClass obj1)
        {
            //To do 
        }

        public void RefreshACCDAHArry(DmClass obj1)
        {
            //To do 
        }

        public void RefreshACCCMArry(DmClass obj1)
        {
            //To do 
        }

        public void RefreshRectStatusArry(DmClass obj1)
        {
            //To do 
        }

        public void RefreshRectPTexpiryArry(DmClass obj1)
        {
            //To do 
        }

        public void RefreshReadCur_step_into_1_stage(DmClass obj1)
        {
            //To do 
        }

        public void RefreshSwitchStatus(DmClass obj1)
        {
            //To do 
        }

        public void RefreshFbarLocArry(DmClass obj1)
        {
            //To do 
        }

        public void RefreshXPProcRecArry(DmClass obj1)
        {
            //To do 
        }

        #region G18030 New Line
        public void RefreshNew_CMM_s_Arry(DmClass obj1)
        {
            //To do
        }

        public void RefreshRECTCODE(DmClass obj1)
        {
            //To do
        }

        public void RefreshACT_AH_Arry(DmClass obj1)
        {
            //To do
        }

        public void RefreshPRE_AH_Arry(DmClass obj1)
        {
            //To do
        }

        public void RefreshACCDAHArry1(DmClass obj1)
        {
            //To do
        }
        #endregion 

        #endregion

        public void Dispose()
        {
            throw new NotImplementedException();
        }

        private Hashtable _formListCollect=new Hashtable();

         /// <summary>
        /// 把窗体添加到Hashtable列表中 (_formListCollect)
        /// </summary>
        /// <param name="Client"></param>
        public void AddFormToList(Form Client)
        {
            //this._FormListLock.AcquireWriterLock(-1);
            try
            {
                this._formListCollect.Add(Client.Name.ToUpper(), Client);
            }
            catch (Exception exception1)
            {
                ProjectData.SetProjectError(exception1);
                this._formListCollect[Client.Name.ToUpper()] = Client;
                ProjectData.ClearProjectError();
            }
            //this._FormListLock.ReleaseWriterLock();
        }

        /// <summary>
        /// 窗体是否存在于集合中
        /// </summary>
        /// <param name="frmName"></param>
        /// <returns></returns>
        public bool FrmExistInCollect(string frmName)
        {
            bool flag;
            try
            {
                flag = this._formListCollect.Contains(frmName.ToUpper());
            }
            catch (Exception exception1)
            {
                ProjectData.SetProjectError(exception1);
                flag = false;
                ProjectData.ClearProjectError();
            }
            return flag;
        }
    }
}
